#include <interfacelib/directx/texture.h>
#include <interfacelib/directx/textureManager.h>
#include <interfacelib/directx/synchronized_dx.h>

using namespace interfacelib::DirectX;

void Texture::drawTexture( RECT *rect, D3DXVECTOR3 *vector, DWORD colorKey , SpriteData *currentSprite , D3DXVECTOR2 *scaling , int degree )
{
	if ( !currentSprite ) return;

	if ( ( currentSprite->textureColSize == 0 ) && ( currentSprite->textureRowSize == 0 ) )
	{
		TextureManager::getInstance()->createTexture( currentSprite );
	}
	{
//		interfacelib::DirectX::Synchronized_Sprite sync_sprite( sprite );
		TextureManager::getInstance()->drawTexture( rect, vector, colorKey, currentSprite, scaling, degree  );
	}
}

void Texture::release()
{
	{
		mapMotion::const_iterator mapIterEnd( m_listMotion->end() );
		for ( mapMotion::const_iterator mapIter = m_listMotion->begin(); mapIter != mapIterEnd ; ++mapIter )
		{
			MotionData *motion = ( *mapIter ).second;
			SAFE_DELETE( motion );
		}
		m_listMotion->clear();
	}
}

void Texture::releaseTexture()
{
	{
		mapMotion::const_iterator mapIterEnd( m_listMotion->end() );
		for ( mapMotion::const_iterator mapIter = m_listMotion->begin(); mapIter != mapIterEnd ; ++mapIter )
		{
			MotionData *motion = ( *mapIter ).second;
			motion->releaseTexture();
		}
	}
}

MotionData *Texture::find( WORD index )
{
	mapMotion::iterator iter = m_listMotion->find( index );
	if ( iter == m_listMotion->end() ) return ( NULL );
	return ( ( *iter ).second );
}


MotionData *Texture::getFirstMotion()
{
	mapMotion::iterator iter = m_listMotion->find( 0 );
	if ( iter == m_listMotion->end() ) return ( NULL );
	return ( ( *iter ).second );
}

MotionData *Texture::getLastMotion()
{
	mapMotion::reverse_iterator iter = m_listMotion->rbegin();
	if ( iter == m_listMotion->rend() ) return ( NULL );
	return ( ( *iter ).second );
}

LPDIRECT3DTEXTURE9 Texture::getSprite( BYTE motionIndex, BYTE frame )
{
	mapMotion::iterator iter = m_listMotion->find( motionIndex );
	if ( iter == m_listMotion->end() ) return ( NULL );


	MotionData *motion = ( *iter ).second;
	if ( motion )
	{
		SpriteData *sprite = motion->getSprite( frame );
		if ( sprite ) return ( sprite->texture[ 0 ] );
	}
	return ( NULL );

}